package com.example.baseutils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.text.TextUtils;
import android.util.Log;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
public class WifiAdmin {
    private String TAG = "WifiAdmin";
    // 定义WifiManager对象
    private WifiManager mWifiManager;
    // 定义WifiInfo对象  
    private WifiInfo mWifiInfo;
    // 扫描出的网络连接列表  
    private List<ScanResult> mWifiList;
    // 网络连接列表  
    private List<WifiConfiguration> mWifiConfiguration;
    // 定义一个WifiLock  
    WifiLock mWifiLock;


    // 构造器  
    public WifiAdmin(Context context) {
        // 取得WifiManager对象  
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象  
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    // 打开WIFI  
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
    }

    // 关闭WIFI  
    public void closeWifi() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    // 检查当前WIFI状态  
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    // 锁定WifiLock  
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解锁WifiLock  
    public void releaseWifiLock() {
        // 判断时候锁定  
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 创建一个WifiLock  
    public void creatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("Test");
    }

    // 得到配置好的网络  
    public List<WifiConfiguration> getConfiguration() {
        return mWifiConfiguration;
    }


    // 指定配置好的网络进行连接  
    public void connectConfiguration(int index) {
        // 索引大于配置好的网络索引返回  
        if (index > mWifiConfiguration.size()) {
            return;
        }
        // 连接配置好的指定ID的网络  
        mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,
                true);
    }

    @SuppressLint("MissingPermission")
    public void startScan() {
        mWifiManager.startScan();
        // 得到扫描结果  
        mWifiList = mWifiManager.getScanResults();
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    }

    // 得到网络列表  
    public List<ScanResult> getWifiList() {
        startScan();
        return mWifiList;
    }

    // 查看扫描结果  
    public StringBuilder lookUpScan() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiList.size(); i++) {
            stringBuilder
                    .append("Index_" + new Integer(i + 1).toString() + ":");
            // 将ScanResult信息转换成一个字符串包  
            // 其中把包括：BSSID、SSID、capabilities、frequency、level  
            stringBuilder.append((mWifiList.get(i)).toString());
            stringBuilder.append("/n");
        }
        return stringBuilder;
    }

    // 得到MAC地址  
    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    // 得到接入点的BSSID  
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    // 得到IP地址  
    public int getIPAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    // 得到连接的ID
    public int getNetworkId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    // 得到连接的SSID
    public String getSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getSSID().replace("\"", "");
    }

    // 得到WifiInfo的所有信息包  
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    // 得到WifiInfo的所有信息包
    public String getWifRssi() {
        return (mWifiInfo == null) ? "NULL" : String.valueOf(mWifiInfo.getRssi());
    }

    // 添加一个网络并连接  
    public boolean addNetwork(WifiConfiguration wcg) {
        int wcgID = mWifiManager.addNetwork(wcg);
        boolean b = mWifiManager.enableNetwork(wcgID, true);
        System.out.println("a--" + wcgID);
        System.out.println("b--" + b);
        return b;
    }

    // 断开指定ID的网络  
    public void disconnectWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

    public boolean connectWifi(String SSID, String PassWd, int Type) {
        boolean addNetwork = addNetwork(CreateWifiInfo(SSID, PassWd, Type));
        return addNetwork;
    }

    //然后是一个实际应用方法，只验证过没有密码的情况：
    public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";

        WifiConfiguration tempConfig = this.IsExsits(SSID);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }
        //如果密码是空的
        if(TextUtils.isEmpty(Password)){
            Type=1;
        }

        if (Type == 1) //WIFICIPHER_NOPASS
        {
            config.wepKeys[0] = "\"\"";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 2) //WIFICIPHER_WEP
        {
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 3) //WIFICIPHER_WPA
        {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    private WifiConfiguration IsExsits(String str) {
        @SuppressLint("MissingPermission") List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals(str.trim())) {
                return existingConfig;
            }
        }
        return null;
    }


    /**
     * 连接静态网络
     */
    public boolean connetStaticWifi(WifiConfiguration mWifiConfiguration, String ipAddress, String gateway, String dns) {
        Log.i(TAG, "连接静态网络: ");
        //移除当前所有保存的网络连接
//        removeAllWifi();
        boolean setStaticIpConfiguration = false;
        try {
            setStaticIpConfiguration =
                    setStaticIpConfiguration(
                            mWifiManager,
                            mWifiConfiguration,
                            InetAddress.getByName(ipAddress), 24,//IP 网络前缀长度24
                            InetAddress.getByName(gateway),//DNS1域名1 gateway
                            InetAddress.getAllByName(dns));//网关

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return setStaticIpConfiguration;
    }

    public boolean setStaticIpConfiguration(final WifiManager manager,
                                            WifiConfiguration config, InetAddress ipAddress, int prefixLength,
                                            InetAddress gateway, InetAddress[] dns)
            throws ClassNotFoundException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException,
            NoSuchMethodException, NoSuchFieldException, InstantiationException {
        // First set up IpAssignment to STATIC.
        Object ipAssignment = getEnumValue(
                "android.net.IpConfiguration$IpAssignment", "STATIC");
        callMethod(config, "setIpAssignment",
                new String[]{"android.net.IpConfiguration$IpAssignment"},
                new Object[]{ipAssignment});

        // Then set properties in StaticIpConfiguration.
        Object staticIpConfig = newInstance("android.net.StaticIpConfiguration");

        Object linkAddress = newInstance("android.net.LinkAddress",
                new Class[]{InetAddress.class, int.class}, new Object[]{
                        ipAddress, prefixLength});
        setField(staticIpConfig, "ipAddress", linkAddress);
        setField(staticIpConfig, "gateway", gateway);
        ArrayList<Object> aa = (ArrayList<Object>) getField(staticIpConfig,
                "dnsServers");
        aa.clear();
        for (int i = 0; i < dns.length; i++)
            aa.add(dns[i]);
        callMethod(config, "setStaticIpConfiguration",
                new String[]{"android.net.StaticIpConfiguration"},
                new Object[]{staticIpConfig});
        int updateNetwork = manager.updateNetwork(config);
        boolean saveConfiguration = manager.saveConfiguration();

        int netId = manager.addNetwork(config);
        manager.disableNetwork(netId);
        boolean flag = manager.enableNetwork(netId, true);

        if (flag) {
            Log.e(TAG, "连接WiFi成功: ");
        } else {
            Log.e(TAG, "连接WiFi失败 --IP不可用: ");
        }
        return flag;
    }

    private static Object newInstance(String className)
            throws ClassNotFoundException, InstantiationException,
            IllegalAccessException, NoSuchMethodException,
            IllegalArgumentException, InvocationTargetException {
        return newInstance(className, new Class[0], new Object[0]);
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    private static Object newInstance(String className,
                                      Class[] parameterClasses, Object[] parameterValues)
            throws NoSuchMethodException, InstantiationException,
            IllegalAccessException, IllegalArgumentException,
            InvocationTargetException, ClassNotFoundException {
        Class clz = Class.forName(className);
        Constructor constructor = clz.getConstructor(parameterClasses);
        return constructor.newInstance(parameterValues);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    private static Object getEnumValue(String enumClassName, String enumValue)
            throws ClassNotFoundException {
        Class enumClz = (Class) Class.forName(enumClassName);
        return Enum.valueOf(enumClz, enumValue);
    }

    private static void setField(Object object, String fieldName, Object value)
            throws IllegalAccessException, IllegalArgumentException,
            NoSuchFieldException {
        Field field = object.getClass().getDeclaredField(fieldName);
        field.set(object, value);
    }

    private static Object getField(Object object, String fieldName)
            throws IllegalAccessException, IllegalArgumentException,
            NoSuchFieldException {
        Field field = object.getClass().getDeclaredField(fieldName);
        Object out = field.get(object);
        return out;
    }

    @SuppressWarnings("rawtypes")
    private static void callMethod(Object object, String methodName,
                                   String[] parameterTypes, Object[] parameterValues)
            throws ClassNotFoundException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException,
            NoSuchMethodException {
        Class[] parameterClasses = new Class[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++)
            parameterClasses[i] = Class.forName(parameterTypes[i]);

        Method method = object.getClass().getDeclaredMethod(methodName,
                parameterClasses);
        method.invoke(object, parameterValues);
    }

    /**
     * 忘记某一个wifi密码
     */
//    public void removeAllWifi() {
//        @SuppressLint("MissingPermission") List<WifiConfiguration> wifiConfigs = mWifiManager.getConfiguredNetworks();
//        if (wifiConfigs != null) {
//            for (WifiConfiguration wifiConfig : wifiConfigs) {
//                //除了默认的不能移除
//                if(wifiConfig.SSID.replace("\"", "").equals(Config.DefaultWifiName)){
//                   continue;
//                }
//                Log.e(TAG, "移除WiFi" + wifiConfig.SSID);
//                if (wifiConfig != null) {
//                    mWifiManager.disableNetwork(wifiConfig.networkId);
//                    mWifiManager.disconnect();
//                    mWifiManager.removeNetwork(wifiConfig.networkId);
//                    mWifiManager.saveConfiguration();
//                }
//            }
//        }
//    }

    /**
     * 忘记某一个wifi密码
     */
//    public void removeWifiBySsid(String SSID) {
//        SSID = "\"" + SSID + "\"";
//        List<WifiConfiguration> wifiConfigs = mWifiManager.getConfiguredNetworks();
//        if (wifiConfigs != null) {
//            for (WifiConfiguration wifiConfig : wifiConfigs) {
//                if (SSID.equals(wifiConfig.SSID)) {
//                    mWifiManager.disableNetwork(wifiConfig.networkId);
//                    mWifiManager.disconnect();
//                    mWifiManager.removeNetwork(wifiConfig.networkId);
//                    mWifiManager.saveConfiguration();
//                    Log.i(TAG, "移除wifi: " + wifiConfig.SSID);
//                }
//            }
//        }
//    }


}
//分为三种情况：1没有密码2用wep加密3用wpa加密